/*
 * Copyright 2006-2023 ahtelit.com, All Rights Reserved.
 */

package com.telit.firecommand.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.LanguageUtils;
import com.telit.dispose.dto.PlatMetaTableEntityDTO;
import com.telit.dispose.entity.dispose.PlatMetaFieldEntity;
import com.telit.dispose.feign.RemoteDisposeService;
import com.telit.dispose.model.QryDeviceListRequest;
import com.telit.dispose.model.QryDeviceModel;
import com.telit.dispose.model.QryResourceModel;
import com.telit.dispose.vo.resourceManagement.DictVO;
import com.telit.dispose.vo.resourceManagement.ResourceCategoryVO;
import com.telit.firecommand.dao.CommFireAlarmDao;
import com.telit.firecommand.dao.DictMapper;
import com.telit.firecommand.dao.FireDisposalInfoDao;
import com.telit.firecommand.dto.FireDisposalInfoDTO;
import com.telit.firecommand.dto.FireQueryListDTO;
import com.telit.firecommand.dto.MultimediaDTO;
import com.telit.firecommand.entity.CommFireAlarm;
import com.telit.firecommand.entity.FireDisposalInfo;
import com.telit.firecommand.model.cityVisualization.*;
import com.telit.firecommand.service.*;
import com.telit.firecommand.vo.CameraVO;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * CityVisualizationServiceImpl
 *
 * @author yuezhuang
 * @since 2023-03-16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CityVisualizationServiceImpl implements CityVisualizationService {

    private final CommFireAlarmDao commFireAlarmDao;

    private final DictMapper dictMapper;

    private final FireDisposalInfoDao fireDisposalInfoDao;

    private final FireQueryService fireQueryService;

    private final RemoteDisposeService remoteDisposeService;

    private final UserInfoService userInfoService;

    private final CameraInfoService cameraInfoService;

    private final CameraMonitorService cameraMonitorService;

    /*
     * 查询物资时需要单独处理的分类名称
     */
    private static final String CATEGORY_NAME_WULIANWANGSHEBEI = "物联网设备";
    private static final String CATEGORY_NAME_WEIQIXIANGZHAN = "微气象站";
    private static final String CATEGORY_NAME_HUOZAITANCEYI = "火灾探测仪";
    private static final String CATEGORY_NAME_SHIPINJIANKONG = "视频监控";
    private static final List<String> CATEGORY_NAME_LIST = Arrays.asList(CATEGORY_NAME_WULIANWANGSHEBEI,
            CATEGORY_NAME_WEIQIXIANGZHAN, CATEGORY_NAME_HUOZAITANCEYI, CATEGORY_NAME_SHIPINJIANKONG);

    //视频监控表名称
    private static final String TABLE_NAME_SHIPINJIANKONG = "comm_camera_info";

    /**
     * 火情统计
     *
     * @param qryFireCountRequest qryFireCountRequest
     *
     * @return QryFireCountModel
     */
    @Override

    public QryFireCountModel qryFireCount(QryFireCountRequest qryFireCountRequest) {
        if (qryFireCountRequest.getDateType() != null) {//近3天、7天、30天
            Integer dateType = qryFireCountRequest.getDateType();
            if (!Arrays.asList(1, 2, 3).contains(dateType)) {
                throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.ARG_BIND_GET.getCode()));
            }
            Date now = new Date();
            String end = DateUtil.format(now, DatePattern.NORM_DATE_PATTERN) + " 23:59:59";
            Calendar ca = Calendar.getInstance();
            ca.setTime(now);
            if (1 == dateType) {
                ca.add(Calendar.DAY_OF_MONTH, -2);
            } else if (2 == dateType) {
                ca.add(Calendar.DAY_OF_MONTH, -6);
            } else if (3 == dateType) {
                ca.add(Calendar.DAY_OF_MONTH, -29);
            }
            String start = DateUtil.format(ca.getTime(), DatePattern.NORM_DATE_PATTERN) + " 00:00:00";
            if (qryFireCountRequest.getStartAt() == null && qryFireCountRequest.getEndAt() == null) {
                qryFireCountRequest.setStartAt(DateUtil.parse(start));
                qryFireCountRequest.setEndAt(DateUtil.parse(end));
            }
        }

        //累计火情数
        LambdaQueryWrapper<CommFireAlarm> totalCountQueryWrapper = new LambdaQueryWrapper<>();
        totalCountQueryWrapper.eq(CommFireAlarm::getHasDelete, 0);
        totalCountQueryWrapper.likeRight(CommFireAlarm::getDistrictCode, qryFireCountRequest.getDistrictCode());
        if (qryFireCountRequest.getStartAt() != null) {
            totalCountQueryWrapper.ge(CommFireAlarm::getFindTime, qryFireCountRequest.getStartAt());
        }
        if (qryFireCountRequest.getEndAt() != null) {
            totalCountQueryWrapper.le(CommFireAlarm::getFindTime, qryFireCountRequest.getEndAt());
        }
        Integer totalCount = commFireAlarmDao.selectCount(totalCountQueryWrapper);

        //非火情数
        LambdaQueryWrapper<CommFireAlarm> notFireCountQueryWrapper = new LambdaQueryWrapper<>();
        notFireCountQueryWrapper.likeRight(CommFireAlarm::getDistrictCode, qryFireCountRequest.getDistrictCode());
        notFireCountQueryWrapper.eq(CommFireAlarm::getHasDelete, 0);
        notFireCountQueryWrapper.eq(CommFireAlarm::getStatus, "6");
        if (qryFireCountRequest.getStartAt() != null) {
            notFireCountQueryWrapper.ge(CommFireAlarm::getFindTime, qryFireCountRequest.getStartAt());
        }
        if (qryFireCountRequest.getEndAt() != null) {
            notFireCountQueryWrapper.le(CommFireAlarm::getFindTime, qryFireCountRequest.getEndAt());
        }
        Integer notFireCount = commFireAlarmDao.selectCount(notFireCountQueryWrapper);

        //重复报警数
        LambdaQueryWrapper<CommFireAlarm> repeatCountQueryWrapper = new LambdaQueryWrapper<>();
        repeatCountQueryWrapper.likeRight(CommFireAlarm::getDistrictCode, qryFireCountRequest.getDistrictCode());
        repeatCountQueryWrapper.eq(CommFireAlarm::getHasDelete, 0);
        repeatCountQueryWrapper.ne(CommFireAlarm::getOriginFireId, Long.parseLong("0"));
        if (qryFireCountRequest.getStartAt() != null) {
            repeatCountQueryWrapper.ge(CommFireAlarm::getFindTime, qryFireCountRequest.getStartAt());
        }
        if (qryFireCountRequest.getEndAt() != null) {
            repeatCountQueryWrapper.le(CommFireAlarm::getFindTime, qryFireCountRequest.getEndAt());
        }
        Integer repeatCount = commFireAlarmDao.selectCount(repeatCountQueryWrapper);

        //重要火情数
        LambdaQueryWrapper<CommFireAlarm> importantCountQueryWrapper = new LambdaQueryWrapper<>();
        importantCountQueryWrapper.likeRight(CommFireAlarm::getDistrictCode, qryFireCountRequest.getDistrictCode());
        importantCountQueryWrapper.eq(CommFireAlarm::getHasDelete, 0);
        importantCountQueryWrapper.in(CommFireAlarm::getFireLevel, Arrays.asList("1", "2", "3", "4"));
        if (qryFireCountRequest.getStartAt() != null) {
            importantCountQueryWrapper.ge(CommFireAlarm::getFindTime, qryFireCountRequest.getStartAt());
        }
        if (qryFireCountRequest.getEndAt() != null) {
            importantCountQueryWrapper.le(CommFireAlarm::getFindTime, qryFireCountRequest.getEndAt());
        }
        Integer importantCount = commFireAlarmDao.selectCount(importantCountQueryWrapper);

        //一般火情数
        Integer commonCount = totalCount - importantCount - notFireCount - repeatCount;

        return QryFireCountModel.builder()
                .totalCount(totalCount)
                .notFireCount(notFireCount)
                .repeatCount(repeatCount)
                .commonCount(commonCount)
                .importantCount(importantCount)
                .build();
    }

    /**
     * 火情趋势
     *
     * @param qryFireTrend30DayRequest qryFireTrend30DayRequest
     *
     * @return QryFireTrend30DayResult
     */
    @Override
    public List<QryFireTrend30DayModel> qryFireTrend30Day(QryFireTrend30DayRequest qryFireTrend30DayRequest) {
        //结束时间
        if (qryFireTrend30DayRequest.getStartAt() == null) {
            qryFireTrend30DayRequest.setStartAt(new Date());
        }
        String end =
                DateUtil.format(qryFireTrend30DayRequest.getStartAt(), DatePattern.NORM_DATE_PATTERN) + " 23:59:59";
        Calendar ca = Calendar.getInstance();
        ca.setTime(qryFireTrend30DayRequest.getStartAt());
        ca.add(Calendar.DAY_OF_MONTH, -29);
        //开始时间
        String start = DateUtil.format(ca.getTime(), DatePattern.NORM_DATE_PATTERN) + " 00:00:00";

        //日期集合
        List<String> dateList = new ArrayList<>();
        Calendar startC = Calendar.getInstance();
        Date startD = DateUtil.parse(start, DatePattern.NORM_DATE_PATTERN);
        startC.setTime(startD);
        Calendar endC = Calendar.getInstance();
        Date endD = DateUtil.parse(end, DatePattern.NORM_DATE_PATTERN);
        endC.setTime(endD);
        dateList.add(DateUtil.format(startC.getTime(), DatePattern.NORM_DATE_PATTERN));
        while (startC.before(endC)) {
            startC.add(Calendar.DATE, 1);
            dateList.add(DateUtil.format(startC.getTime(), DatePattern.NORM_DATE_PATTERN));
        }

        //查询数据
        List<QryFireTrend30DayModel> list = commFireAlarmDao.qryFireTrend30Day(
                qryFireTrend30DayRequest.getDistrictCode(), start, end);
        Map<String, QryFireTrend30DayModel> dataMap = list.stream().collect(
                Collectors.toMap(QryFireTrend30DayModel::getDay, Function.identity(), (key1, key2) -> key2));

        List<QryFireTrend30DayModel> result = new ArrayList<>();
        dateList.forEach(day -> {
            QryFireTrend30DayModel qryFireTrend30DayModel = dataMap.get(day);
            if (qryFireTrend30DayModel == null) {
                qryFireTrend30DayModel = QryFireTrend30DayModel.builder().day(day).totalCount(0).build();
            }
            result.add(qryFireTrend30DayModel);
        });

        return result;
    }

    /**
     * 火灾统计
     *
     * @param qryFireTrend1YearRequest qryFireTrend1YearRequest
     *
     * @return QryFireTrend1YearResult
     */
    @Override
    public List<Map<String, List<QryFireTrend1YearResult.LevelCount>>> qryFireTrend1Year(
            QryFireTrend1YearRequest qryFireTrend1YearRequest) {
        if (qryFireTrend1YearRequest.getStartAt() == null) {
            qryFireTrend1YearRequest.setStartAt(new Date());
        }
        //结束时间
        //当月最后一天
        Calendar ca = Calendar.getInstance();
        ca.setTime(qryFireTrend1YearRequest.getStartAt());
        int actualMaximum = ca.getActualMaximum(Calendar.DATE);
        String end =
                DateUtil.format(qryFireTrend1YearRequest.getStartAt(), "yyyy-MM") + "-" + actualMaximum + " 23:59:59";
        ca.add(Calendar.MONTH, -11);
        //开始时间
        String start = DateUtil.format(ca.getTime(), "yyyy-MM") + "-01 00:00:00";

        //日期集合
        List<String> dateList = new ArrayList<>();
        Calendar startC = Calendar.getInstance();
        Date startD = DateUtil.parse(start, "yyyy-MM");
        startC.setTime(startD);
        Calendar endC = Calendar.getInstance();
        Date endD = DateUtil.parse(end, "yyyy-MM");
        endC.setTime(endD);
        dateList.add(DateUtil.format(startC.getTime(), "yyyy-MM"));
        while (startC.before(endC)) {
            startC.add(Calendar.MONTH, 1);
            dateList.add(DateUtil.format(startC.getTime(), "yyyy-MM"));
        }

        //火险等级
        List<DictVO> dictVOList = dictMapper.listByParentCode("fire_level");
        Map<String, String> dictMap = dictVOList.stream().collect(
                Collectors.toMap(DictVO::getCode, DictVO::getName, (e1, e2) -> e1));

        //查询数据
        List<QryFireTrend1YearModel> list = commFireAlarmDao.qryFireTrend1Year(
                qryFireTrend1YearRequest.getDistrictCode(), start, end);
        Map<String, List<QryFireTrend1YearResult.LevelCount>> day2Result = new HashMap<>();
        list.forEach(qryFireTrend1YearModel -> {
            String day = qryFireTrend1YearModel.getDay();
            //火情等级为空时，当做一般火情 fire_level = 5
            if (StrUtil.isEmpty(qryFireTrend1YearModel.getFireLevel()) || StrUtil.equals("5",
                    qryFireTrend1YearModel.getFireLevel())) {
                Integer totalCount = qryFireTrend1YearModel.getTotalCount();
                //一般火情数
                List<QryFireTrend1YearResult.LevelCount> levelCounts = day2Result.get(day);
                if (levelCounts == null) {
                    levelCounts = new ArrayList<>();
                }
                Integer fireLevel5 = 0;
                Iterator<QryFireTrend1YearResult.LevelCount> iterator = levelCounts.iterator();
                while (iterator.hasNext()) {
                    QryFireTrend1YearResult.LevelCount next = iterator.next();
                    if (StrUtil.equals("5", next.getFireLevel())) {
                        fireLevel5 = next.getTotalCount();
                        iterator.remove();
                    }
                }
                fireLevel5 += totalCount;
                levelCounts.add(QryFireTrend1YearResult.LevelCount.builder()
                        .totalCount(fireLevel5)
                        .fireLevel("5")
                        .levelName(dictMap.get("5"))
                        .build());
                day2Result.put(day, levelCounts);
            } else {
                List<QryFireTrend1YearResult.LevelCount> levelCounts = day2Result.get(day);
                if (levelCounts == null) {
                    levelCounts = new ArrayList<>();
                }
                levelCounts.add(QryFireTrend1YearResult.LevelCount.builder()
                        .totalCount(qryFireTrend1YearModel.getTotalCount())
                        .fireLevel(qryFireTrend1YearModel.getFireLevel())
                        .levelName(dictMap.get(qryFireTrend1YearModel.getFireLevel()))
                        .build());
                day2Result.put(day, levelCounts);
            }
        });

        //按照日期排序
        List<Map<String, List<QryFireTrend1YearResult.LevelCount>>> result = new ArrayList<>();
        dateList.forEach(day -> {
            Map<String, List<QryFireTrend1YearResult.LevelCount>> item = new HashMap<>();
            List<QryFireTrend1YearResult.LevelCount> levelCounts = day2Result.get(day);
            if (levelCounts == null) {
                levelCounts = new ArrayList<>();
            }
            item.put(day, levelCounts);
            result.add(item);
        });

        return result;
    }

    /**
     * 火情列表
     *
     * @param qryFireListRequest qryFireListRequest
     *
     * @return QryFireListModel
     */
    @Override
    public PageData<List<QryFireListModel>> qryFireList(QryFireListRequest qryFireListRequest) {
        if (qryFireListRequest.getDateType() != null) {//近3天、7天、30天
            Integer dateType = qryFireListRequest.getDateType();
            if (!Arrays.asList(1, 2, 3).contains(dateType)) {
                throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.ARG_BIND_GET.getCode()));
            }
            Date now = new Date();
            String end = DateUtil.format(now, DatePattern.NORM_DATE_PATTERN) + " 23:59:59";
            Calendar ca = Calendar.getInstance();
            ca.setTime(now);
            if (1 == dateType) {
                ca.add(Calendar.DAY_OF_MONTH, -2);
            } else if (2 == dateType) {
                ca.add(Calendar.DAY_OF_MONTH, -6);
            } else if (3 == dateType) {
                ca.add(Calendar.DAY_OF_MONTH, -29);
            }
            String start = DateUtil.format(ca.getTime(), DatePattern.NORM_DATE_PATTERN) + " 00:00:00";
            if (qryFireListRequest.getStartAt() == null && qryFireListRequest.getEndAt() == null) {
                qryFireListRequest.setStartAt(DateUtil.parse(start));
                qryFireListRequest.setEndAt(DateUtil.parse(end));
            }
        }
        FireQueryListDTO fireQueryListDTO = FireQueryListDTO.builder()
                .districtCode(qryFireListRequest.getDistrictCode())
                .fireName(qryFireListRequest.getFireName())
                .page(qryFireListRequest.getCurrent())
                .rows(qryFireListRequest.getSize())
                .build();
        if (qryFireListRequest.getStartAt() != null) {
            fireQueryListDTO.setStartTime(
                    DateUtil.format(qryFireListRequest.getStartAt(), DatePattern.NORM_DATETIME_PATTERN));
        }
        if (qryFireListRequest.getEndAt() != null) {
            fireQueryListDTO.setEndTime(
                    DateUtil.format(qryFireListRequest.getEndAt(), DatePattern.NORM_DATETIME_PATTERN));
        }
//        fireQueryListDTO.setFireLevels(qryFireListRequest.getFireLevels());
        fireQueryListDTO.setFireTypes(qryFireListRequest.getFireTypes());

        //火险等级
        List<DictVO> dictVOList = dictMapper.listByParentCode("fire_level");
        Map<String, String> dictMap = dictVOList.stream().collect(
                Collectors.toMap(DictVO::getCode, DictVO::getName, (e1, e2) -> e1));

        PageData<List<CommFireAlarm>> pageData = fireQueryService.queryAllFireByCondition(fireQueryListDTO);
        List<CommFireAlarm> datas = pageData.getDatas();
        List<QryFireListModel> fireListModels = new ArrayList<>();
        datas.forEach(commFireAlarm -> {
            fireListModels.add(QryFireListModel.builder()
                    .id(commFireAlarm.getId())
                    .fireName(commFireAlarm.getContent())
                    .detailAddress(commFireAlarm.getDetailAddress())
                    .findTime(commFireAlarm.getFindTime())
                    .longitude(commFireAlarm.getLongitude())
                    .latitude(commFireAlarm.getLatitude())
                    .fireLevel(commFireAlarm.getFireLevel())
                    .fireLevelName(
                            commFireAlarm.getFireLevel() != null ? dictMap.get(commFireAlarm.getFireLevel()) : null)
                    .build());
        });

        return PageData.<List<QryFireListModel>>builder()
                .count(pageData.getCount())
                .current(pageData.getCurrent())
                .size(pageData.getSize())
                .datas(fireListModels)
                .build();
    }

    /**
     * 火情详情
     *
     * @param id id
     *
     * @return QryFireDetailModel
     */
    @Override
    public QryFireDetailModel qryFireDetail(Long id) {
        //火情
        CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(id);
        if (commFireAlarm == null) {
            throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), id));
        }

        //多媒体信息
        Map<String, List<MultimediaDTO>> stringListMap = fireQueryService.queryOnlyAddMediaById(id);

        //处置信息
        List<FireDisposalInfo> fireDisposalList = fireDisposalInfoDao.queryFireDisposalInfoByFireId(id);
        List<FireDisposalInfoDTO> fireDisposalInfoDTOS = fireDisposalList.stream().map(
                map -> Convert.convert(FireDisposalInfoDTO.class, map)).collect(
                Collectors.toList());

        //火情状态常量
        List<DictVO> dictVOList = dictMapper.listByParentCode("fire_status");
        Map<String, String> dictMap = dictVOList.stream().collect(
                Collectors.toMap(DictVO::getCode, DictVO::getName, (e1, e2) -> e1));

        //联系人手机号
        String findMobile = commFireAlarm.getTelephoneNumber();
        if (StrUtil.isBlank(findMobile)) {
            if (commFireAlarm.getFinderId() != null) {
                MicroSysUserAllInfoVo userInfo = userInfoService.getUserInfo(commFireAlarm.getFinderId());
                findMobile = userInfo.getMobile();
            }
        }

        return QryFireDetailModel.builder()
                .id(commFireAlarm.getId())
                .fireName(commFireAlarm.getContent())
                .finderMobile(findMobile)
                .detailAddress(commFireAlarm.getDetailAddress())
                .longitude(commFireAlarm.getLongitude())
                .latitude(commFireAlarm.getLatitude())
                .finderName(commFireAlarm.getFinderName())
                .findTime(commFireAlarm.getFindTime())
                .status(commFireAlarm.getStatus())
                .statusName(dictMap.get(commFireAlarm.getStatus()))
                .imgList(stringListMap.get("imgList"))
                .videoList(stringListMap.get("videoList"))
                .audioList(stringListMap.get("audioList"))
                .docList(stringListMap.get("docList"))
                .fireDisposalList(fireDisposalInfoDTOS)
                .build();
    }

    /**
     * 实时视频流
     *
     * @param fireId 火情id
     *
     * @return QryCameraUrlModel
     */
    @Override
    public QryCameraUrlModel qryCameraUrl(Long fireId, String cameraId, Integer type) {
        Long deviceId = null;
        if (StrUtil.isNotEmpty(cameraId)) {
            deviceId = Long.parseLong(cameraId);
        } else {
            CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
            if (commFireAlarm == null) {
                throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), fireId));
            }
            deviceId = commFireAlarm.getDeviceId();
            if (deviceId == null) {
                throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), fireId));
            }
        }

        CameraVO info = cameraInfoService.info(deviceId.toString());
        if (info == null) {
            throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), fireId));
        }
        String codes = info.getCameraId();
        String[] codeList = codes.split(",");
        // 可见光
        String visibleLightUrl = null;
        // 热成像
        String thermalImagingUrl = null;
        if (1 == type) {
            visibleLightUrl = cameraMonitorService.queryRtspUrl(codeList[0]);
            if (codeList.length == 2) {
                thermalImagingUrl = cameraMonitorService.queryRtspUrl(codeList[1]);
            }
        } else {
            visibleLightUrl = cameraMonitorService.queryFlvpUrl(codeList[0]);
            if (codeList.length == 2) {
                thermalImagingUrl = cameraMonitorService.queryFlvpUrl(codeList[1]);
            }
        }
        return QryCameraUrlModel.builder()
                .visibleLightUrl(visibleLightUrl)
                .thermalImagingUrl(thermalImagingUrl)
                .build();
    }

    /**
     * 历史视频流
     *
     * @param qryCameraHistoryUrlRequest qryCameraHistoryUrlRequest
     *
     * @return QryCameraHistoryUrlModel
     */
    @Override
    public QryCameraHistoryUrlModel qryCameraHistoryUrl(QryCameraHistoryUrlRequest qryCameraHistoryUrlRequest) {
        Long deviceId = null;
        Long fireId = qryCameraHistoryUrlRequest.getFireId();
//        Integer type = qryCameraHistoryUrlRequest.getType();
        String cameraId = qryCameraHistoryUrlRequest.getCameraId();
        if (StrUtil.isNotEmpty(cameraId)) {
            deviceId = Long.parseLong(cameraId);
        } else {
            CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
            if (commFireAlarm == null) {
                throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), fireId));
            }
            deviceId = commFireAlarm.getDeviceId();
            if (deviceId == null) {
                throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), fireId));
            }
        }

        CameraVO info = cameraInfoService.info(deviceId.toString());
        if (info == null) {
            throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), fireId));
        }
        String codes = info.getCameraId();
        String[] codeList = codes.split(",");
        // 可见光
        String visibleLightUrl = cameraMonitorService.playbackURLs(codeList[0],
                DateUtil.format(qryCameraHistoryUrlRequest.getStartAt(), DatePattern.NORM_DATETIME_PATTERN),
                DateUtil.format(qryCameraHistoryUrlRequest.getEndAt(), DatePattern.NORM_DATETIME_PATTERN), null,
                null);
        // 热成像
        String thermalImagingUrl = null;
        if (codeList.length == 2) {
            thermalImagingUrl = cameraMonitorService.playbackURLs(codeList[1],
                    DateUtil.format(qryCameraHistoryUrlRequest.getStartAt(), DatePattern.NORM_DATETIME_PATTERN),
                    DateUtil.format(qryCameraHistoryUrlRequest.getEndAt(), DatePattern.NORM_DATETIME_PATTERN), null,
                    null);
        }

        return QryCameraHistoryUrlModel.builder()
                .visibleLightUrl(visibleLightUrl)
                .thermalImagingUrl(thermalImagingUrl)
                .build();
    }

    /**
     * 物资统计（过滤“物资设备”）
     *
     * @param qryResourceCountRequest qryResourceCountRequest
     *
     * @return QryResourceCountModel
     */
    @Override
    public List<QryResourceCountModel> qryResourceCount(QryResourceCountRequest qryResourceCountRequest) {
        //分类
        DataReturn<List<ResourceCategoryVO>> listDataReturn = remoteDisposeService.topFloorDownChildrenList(0L, null,
                null, null, qryResourceCountRequest.getDistrictCode());
        if (!ResultCode.SUCCESS.getCode().equals(listDataReturn.getCode())) {
            throw new ForestBaseException(listDataReturn.getErrorMsg());
        }
        List<ResourceCategoryVO> resourceCategoryVOS = listDataReturn.getData();
        resourceCategoryVOS = resourceCategoryVOS.stream()
                .filter(resourceCategoryVO -> !CATEGORY_NAME_LIST.contains(resourceCategoryVO.getResourceName()))
                .peek(resourceCategoryVO -> {
                    List<Map> resourceList = resourceCategoryVO.getResourceList();
                    resourceList = resourceList.stream().filter(
                            map -> !CATEGORY_NAME_LIST.contains(MapUtil.getStr(map, "resourceName"))).collect(
                            Collectors.toList());
                    resourceCategoryVO.setResourceList(resourceList);
                }).collect(Collectors.toList());

        //格式化数据
        List<QryResourceCountModel> resourceCountModels = new ArrayList<>();
        resourceCategoryVOS.forEach(resourceCategoryVO -> {
            List<Map> resourceList = resourceCategoryVO.getResourceList();
            List<QryResourceCountModel> child = new ArrayList<>();
            resourceList.forEach(map -> {
                child.add(QryResourceCountModel.builder()
                        .id(MapUtil.getStr(map, "tableId"))
                        .catName(MapUtil.getStr(map, "resourceName"))
                        .rank(2)
                        .totalCount(MapUtil.getInt(map, "resourceCount"))
                        .child(new ArrayList<>())
                        .build());
            });
            QryResourceCountModel build = QryResourceCountModel.builder()
                    .id(String.valueOf(resourceCategoryVO.getId()))
                    .catName(resourceCategoryVO.getResourceName())
                    .rank(1)
                    .totalCount(resourceCategoryVO.getCategoryNum())
                    .child(child)
                    .build();
            resourceCountModels.add(build);
        });

        return resourceCountModels;
    }

    /**
     * 物资列表
     *
     * @param qryResourceListRequest qryResourceListRequest
     *
     * @return QryResourceListModel
     */
    @Override
    public PageData<List<QryResourceListModel>> qryResourceList(QryResourceListRequest qryResourceListRequest) {
        //所有设施分类
        List<QryResourceCatModel> qryResourceCatModels = qryResourceCat(
                QryResourceCatRequest.builder().districtCode(qryResourceListRequest.getDistrictCode()).build());

        //分类id 分类名称
        Map<String, String> tableId2TableName = new HashMap<>();
        //分类id 大类
        Map<String, String> tableId2ParentName = new HashMap<>();
        qryResourceCatModels.forEach(qryResourceCatModel -> {
            List<QryResourceCatModel> child = qryResourceCatModel.getChild();
            child.forEach(qryResourceCatModel1 -> {
                tableId2TableName.put(qryResourceCatModel1.getId(), qryResourceCatModel1.getCatName());
                tableId2ParentName.put(qryResourceCatModel1.getId(), qryResourceCatModel.getCatName());
            });
            tableId2TableName.put(qryResourceCatModel.getId(), qryResourceCatModel.getCatName());
        });

        //筛选所有二级分类
        List<String> tableIdList = new ArrayList<>();
        if (StrUtil.isNotEmpty(qryResourceListRequest.getCatIds())) {
            List<String> catIds = Arrays.asList(qryResourceListRequest.getCatIds().split(","));
            qryResourceCatModels.forEach(qryResourceCatModel -> {
                List<QryResourceCatModel> child = qryResourceCatModel.getChild();
                List<String> tableIds;
                if (catIds.contains(qryResourceCatModel.getId())) {//命中一级分类，则把一级分类的子分类全部添加
                    tableIds = child.stream().map(QryResourceCatModel::getId).collect(Collectors.toList());
                } else {
                    tableIds = child.stream().map(QryResourceCatModel::getId).filter(
                            catIds::contains).collect(Collectors.toList());
                }
                tableIdList.addAll(tableIds);
            });
        } else if (StrUtil.isNotEmpty(qryResourceListRequest.getCatId())
                && qryResourceListRequest.getRank() != null) {
            if (qryResourceListRequest.getRank() == 1) {
                qryResourceCatModels.stream().filter(qryResourceCatModel -> {
                    if (qryResourceListRequest.getCatId().equals(qryResourceCatModel.getId())) {
                        return true;
                    }
                    return false;
                }).forEach(qryResourceCatModel -> {
                    List<QryResourceCatModel> child = qryResourceCatModel.getChild();
                    List<String> tableIds = child.stream().map(QryResourceCatModel::getId).collect(
                            Collectors.toList());
                    tableIdList.addAll(tableIds);
                });
            } else if (qryResourceListRequest.getRank() == 2) {
                qryResourceCatModels.forEach(qryResourceCatModel -> {
                    List<QryResourceCatModel> child = qryResourceCatModel.getChild();
                    List<String> tableIds = child.stream().filter(qryResourceCatModel1 -> {
                        if (qryResourceListRequest.getCatId().equals(qryResourceCatModel1.getId())) {
                            return true;
                        }
                        return false;
                    }).map(QryResourceCatModel::getId).collect(Collectors.toList());
                    tableIdList.addAll(tableIds);
                });
            }
        } else {
            qryResourceCatModels.forEach(qryResourceCatModel -> {
                List<QryResourceCatModel> child = qryResourceCatModel.getChild();
                List<String> tableIds = child.stream().map(QryResourceCatModel::getId).collect(Collectors.toList());
                tableIdList.addAll(tableIds);
            });
        }

        //根据分类分页查询物资列表
        com.telit.dispose.model.QryResourceListRequest qryDeviceListRequest = com.telit.dispose.model.QryResourceListRequest.builder()
                .districtCode(qryResourceListRequest.getDistrictCode())
                .resourceName(qryResourceListRequest.getResourceName())
                .tableIds(tableIdList)
                .current(qryResourceListRequest.getCurrent() == null ? 1 : qryResourceListRequest.getCurrent())
                .size(qryResourceListRequest.getSize() == null ? 20 : qryResourceListRequest.getSize())
                .build();
        DataReturn<PageData<List<QryResourceModel>>> pageDataDataReturn = remoteDisposeService.qryResourceList(
                qryDeviceListRequest);
        if (!ResultCode.SUCCESS.getCode().equals(pageDataDataReturn.getCode())) {
            throw new ForestBaseException(pageDataDataReturn.getErrorMsg());
        }
        PageData<List<QryResourceModel>> pageData = pageDataDataReturn.getData();

        //设备列表
        List<QryResourceListModel> qryResourceListModels = pageData.getDatas().stream().map(
                qryDeviceModel -> Convert.convert(QryResourceListModel.class, qryDeviceModel)).collect(
                Collectors.toList());
        qryResourceListModels = qryResourceListModels.stream().peek(qryResourceListModel -> {
            qryResourceListModel.setCatName(tableId2TableName.get(qryResourceListModel.getTableId()));
            qryResourceListModel.setParentCatName(tableId2ParentName.get(qryResourceListModel.getTableId()));
        }).collect(Collectors.toList());

        return PageData.<List<QryResourceListModel>>builder()
                .count(pageData.getCount())
                .current(pageData.getCurrent())
                .size(pageData.getSize())
                .datas(qryResourceListModels)
                .build();
    }

    /**
     * 物资详情
     *
     * @param tableId tableId
     * @param id      id
     *
     * @return QryResourceDetailModel
     */
//    @Override
//    public QryResourceDetailModel qryResourceDetail(String tableId, String id) {
//        DataReturn<QryResourceModel> qryResourceModelDataReturn = remoteDisposeService.qryResourceDetail(tableId, id);
//        if (!ResultCode.SUCCESS.getCode().equals(qryResourceModelDataReturn.getCode())) {
//            throw new ForestBaseException(qryResourceModelDataReturn.getErrorMsg());
//        }
//        QryResourceDetailModel resourceDetailModel = new QryResourceDetailModel();
//        BeanUtils.copyProperties(qryResourceModelDataReturn.getData(), resourceDetailModel);
//
//        //所有设施分类
//        List<QryResourceCatModel> qryResourceCatModels = qryResourceCat(
//                QryResourceCatRequest.builder().districtCode(resourceDetailModel.getDistrictCode()).build());
//
//        //分类id 分类名称
//        Map<String, String> tableId2TableName = new HashMap<>();
//        //分类id 大类
//        Map<String, String> tableId2ParentName = new HashMap<>();
//        qryResourceCatModels.forEach(qryResourceCatModel -> {
//            List<QryResourceCatModel> child = qryResourceCatModel.getChild();
//            child.forEach(qryResourceCatModel1 -> {
//                tableId2TableName.put(qryResourceCatModel1.getId(), qryResourceCatModel1.getCatName());
//                tableId2ParentName.put(qryResourceCatModel1.getId(), qryResourceCatModel.getCatName());
//            });
//            tableId2TableName.put(qryResourceCatModel.getId(), qryResourceCatModel.getCatName());
//        });
//        resourceDetailModel.setCatName(tableId2TableName.get(resourceDetailModel.getTableId()));
//        resourceDetailModel.setParentCatName(tableId2ParentName.get(resourceDetailModel.getTableId()));
//
//        return resourceDetailModel;
//    }
    @Override
    public Map<String, Object> qryResourceDetail(String tableId, String id) {
        return qryResourceEquipmentDetail(tableId, id);
    }

    /**
     * 设施统计
     *
     * @param qryResourceEquipmentCountRequest qryResourceEquipmentCountRequest
     *
     * @return QryResourceEquipmentCountModel
     */
    @Override
    public List<QryResourceEquipmentCountModel> qryResourceEquipmentCount(
            QryResourceEquipmentCountRequest qryResourceEquipmentCountRequest) {
        //分类
        DataReturn<List<ResourceCategoryVO>> listDataReturn = remoteDisposeService.topFloorDownChildrenList(0L, null,
                null, null, qryResourceEquipmentCountRequest.getDistrictCode());
        if (!ResultCode.SUCCESS.getCode().equals(listDataReturn.getCode())) {
            throw new ForestBaseException(listDataReturn.getErrorMsg());
        }
        List<ResourceCategoryVO> resourceCategoryVOS = listDataReturn.getData();
        resourceCategoryVOS = resourceCategoryVOS.stream()
                .filter(resourceCategoryVO -> CATEGORY_NAME_LIST.contains(resourceCategoryVO.getResourceName()))
                .peek(resourceCategoryVO -> {
                    List<Map> resourceList = resourceCategoryVO.getResourceList();
                    resourceList = resourceList.stream().filter(
                            map -> CATEGORY_NAME_LIST.contains(MapUtil.getStr(map, "resourceName"))).collect(
                            Collectors.toList());
                    resourceCategoryVO.setResourceList(resourceList);
                }).collect(Collectors.toList());

        //格式化数据
        List<QryResourceEquipmentCountModel> resourceCountModels = new ArrayList<>();
        resourceCategoryVOS.forEach(resourceCategoryVO -> {
            List<Map> resourceList = resourceCategoryVO.getResourceList();
            List<QryResourceEquipmentCountModel> child = new ArrayList<>();
            resourceList.forEach(map -> {
                child.add(QryResourceEquipmentCountModel.builder()
                        .id(MapUtil.getStr(map, "tableId"))
                        .catName(MapUtil.getStr(map, "resourceName"))
                        .rank(2)
                        .totalCount(MapUtil.getInt(map, "resourceCount"))
                        .child(new ArrayList<>())
                        .build());
            });
            QryResourceEquipmentCountModel build = QryResourceEquipmentCountModel.builder()
                    .id(String.valueOf(resourceCategoryVO.getId()))
                    .catName(resourceCategoryVO.getResourceName())
                    .rank(1)
                    .totalCount(resourceCategoryVO.getCategoryNum())
                    .child(child)
                    .build();
            resourceCountModels.add(build);
        });
        return resourceCountModels;
    }

    /**
     * 设施列表
     *
     * @param qryResourceEquipmentListRequest qryResourceEquipmentListRequest
     *
     * @return QryResourceEquipmentListModel
     */
    @Override
    public PageData<List<QryResourceEquipmentListModel>> qryResourceEquipmentList(
            QryResourceEquipmentListRequest qryResourceEquipmentListRequest) {
        //所有设施分类
        List<QryEquipmentCatModel> qryEquipmentCatModels = qryEquipmentCat(
                QryEquipmentCatRequest.builder().districtCode(
                        qryResourceEquipmentListRequest.getDistrictCode()).build());

        //分类id 分类名称
        Map<String, String> tableId2TableName = new HashMap<>();
        qryEquipmentCatModels.forEach(qryEquipmentCatModel -> {
            List<QryEquipmentCatModel> child = qryEquipmentCatModel.getChild();
            child.forEach(qryEquipmentCatModel1 -> {
                tableId2TableName.put(qryEquipmentCatModel1.getId(), qryEquipmentCatModel1.getCatName());
            });
            tableId2TableName.put(qryEquipmentCatModel.getId(), qryEquipmentCatModel.getCatName());
        });

        //筛选所有二级分类
        List<String> tableIdList = new ArrayList<>();
        if (StrUtil.isNotEmpty(qryResourceEquipmentListRequest.getCatIds())) {
            List<String> catIds = Arrays.asList(qryResourceEquipmentListRequest.getCatIds().split(","));
            qryEquipmentCatModels.forEach(qryEquipmentCatModel -> {
                List<QryEquipmentCatModel> child = qryEquipmentCatModel.getChild();
                List<String> tableIds;
                if (catIds.contains(qryEquipmentCatModel.getId())) {//命中一级分类，则把一级分类的子分类全部添加
                    tableIds = child.stream().map(QryEquipmentCatModel::getId).collect(Collectors.toList());
                } else {
                    tableIds = child.stream().map(QryEquipmentCatModel::getId).filter(
                            catIds::contains).collect(Collectors.toList());
                }
                tableIdList.addAll(tableIds);
            });
        } else if (StrUtil.isNotEmpty(qryResourceEquipmentListRequest.getCatId())
                && qryResourceEquipmentListRequest.getRank() != null) {
            if (qryResourceEquipmentListRequest.getRank() == 1) {
                qryEquipmentCatModels.stream().filter(qryEquipmentCatModel -> {
                    if (qryResourceEquipmentListRequest.getCatId().equals(qryEquipmentCatModel.getId())) {
                        return true;
                    }
                    return false;
                }).forEach(qryEquipmentCatModel -> {
                    List<QryEquipmentCatModel> child = qryEquipmentCatModel.getChild();
                    List<String> tableIds = child.stream().map(QryEquipmentCatModel::getId).collect(
                            Collectors.toList());
                    tableIdList.addAll(tableIds);
                });
            } else if (qryResourceEquipmentListRequest.getRank() == 2) {
                qryEquipmentCatModels.forEach(qryEquipmentCatModel -> {
                    List<QryEquipmentCatModel> child = qryEquipmentCatModel.getChild();
                    List<String> tableIds = child.stream().filter(qryEquipmentCatModel1 -> {
                        if (qryResourceEquipmentListRequest.getCatId().equals(qryEquipmentCatModel1.getId())) {
                            return true;
                        }
                        return false;
                    }).map(QryEquipmentCatModel::getId).collect(Collectors.toList());
                    tableIdList.addAll(tableIds);
                });
            }
        } else {
            qryEquipmentCatModels.forEach(qryEquipmentCatModel -> {
                List<QryEquipmentCatModel> child = qryEquipmentCatModel.getChild();
                List<String> tableIds = child.stream().map(QryEquipmentCatModel::getId).collect(Collectors.toList());
                tableIdList.addAll(tableIds);
            });
        }

        //根据分类分页查询物资列表
        QryDeviceListRequest qryDeviceListRequest = QryDeviceListRequest.builder()
                .districtCode(qryResourceEquipmentListRequest.getDistrictCode())
                .resourceName(qryResourceEquipmentListRequest.getResourceName())
                .deviceStatus(qryResourceEquipmentListRequest.getDeviceStatus())
                .netStatus(qryResourceEquipmentListRequest.getNetStatus())
                .tableIds(tableIdList)
                .current(qryResourceEquipmentListRequest.getCurrent() == null ? 1
                        : qryResourceEquipmentListRequest.getCurrent())
                .size(qryResourceEquipmentListRequest.getSize() == null ? 20
                        : qryResourceEquipmentListRequest.getSize())
                .build();
        DataReturn<PageData<List<QryDeviceModel>>> pageDataDataReturn = remoteDisposeService.qryDeviceList(
                qryDeviceListRequest);
        if (!ResultCode.SUCCESS.getCode().equals(pageDataDataReturn.getCode())) {
            throw new ForestBaseException(pageDataDataReturn.getErrorMsg());
        }
        PageData<List<QryDeviceModel>> pageData = pageDataDataReturn.getData();

        //设备状态
        List<DictVO> deviceList = dictMapper.listByParentCode("device_status");
        Map<String, String> deviceMap = deviceList.stream().collect(
                Collectors.toMap(DictVO::getCode, DictVO::getName, (e1, e2) -> e1));

        //网络状态
        List<DictVO> netList = dictMapper.listByParentCode("net_status");
        Map<String, String> netMap = netList.stream().collect(
                Collectors.toMap(DictVO::getCode, DictVO::getName, (e1, e2) -> e1));

        //设备列表
        List<QryResourceEquipmentListModel> resourceEquipmentListModels = pageData.getDatas().stream().map(
                qryDeviceModel -> Convert.convert(QryResourceEquipmentListModel.class, qryDeviceModel)).collect(
                Collectors.toList());
        resourceEquipmentListModels = resourceEquipmentListModels.stream().peek(qryResourceEquipmentListModel -> {
            qryResourceEquipmentListModel.setCatName(tableId2TableName.get(qryResourceEquipmentListModel.getTableId()));
            qryResourceEquipmentListModel.setDeviceStatusName(
                    deviceMap.get(qryResourceEquipmentListModel.getDeviceStatus()));
            qryResourceEquipmentListModel.setNetStatusName(netMap.get(qryResourceEquipmentListModel.getNetStatus()));
        }).collect(Collectors.toList());

        return PageData.<List<QryResourceEquipmentListModel>>builder()
                .count(pageData.getCount())
                .current(pageData.getCurrent())
                .size(pageData.getSize())
                .datas(resourceEquipmentListModels)
                .build();
    }

    /**
     * 设施详情
     *
     * @param tableId tableId
     * @param id      id
     *
     * @return QryResourceEquipmentDetailModel
     */
//    @Override
//    public QryResourceEquipmentDetailModel qryResourceEquipmentDetail(String tableId, String id) {
//        DataReturn<QryDeviceModel> qryDeviceModelDataReturn = remoteDisposeService.qryDeviceDetail(tableId, id);
//        if (!ResultCode.SUCCESS.getCode().equals(qryDeviceModelDataReturn.getCode())) {
//            throw new ForestBaseException(qryDeviceModelDataReturn.getErrorMsg());
//        }
//        QryResourceEquipmentDetailModel qryResourceEquipmentDetailModel = new QryResourceEquipmentDetailModel();
//        BeanUtils.copyProperties(qryDeviceModelDataReturn.getData(), qryResourceEquipmentDetailModel);
//
//        //所有设施分类
//        List<QryEquipmentCatModel> qryEquipmentCatModels = qryEquipmentCat(
//                QryEquipmentCatRequest.builder().districtCode(
//                        qryResourceEquipmentDetailModel.getDistrictCode()).build());
//        //分类id 分类名称
//        Map<String, String> tableId2TableName = new HashMap<>();
//        qryEquipmentCatModels.forEach(qryEquipmentCatModel -> {
//            List<QryEquipmentCatModel> child = qryEquipmentCatModel.getChild();
//            child.forEach(qryEquipmentCatModel1 -> {
//                tableId2TableName.put(qryEquipmentCatModel1.getId(), qryEquipmentCatModel1.getCatName());
//            });
//        });
//        qryResourceEquipmentDetailModel.setCatName(tableId2TableName.get(qryResourceEquipmentDetailModel.getTableId()));
//
//        return qryResourceEquipmentDetailModel;
//    }
    @Override
    public Map<String, Object> qryResourceEquipmentDetail(String tableId, String id) {
        //判断是否是视频监控
        DataReturn<PlatMetaTableEntityDTO> platMetaTableEntityDTODataReturn = remoteDisposeService.selectTableByTableId(
                tableId);
        if (!ResultCode.SUCCESS.getCode().equals(platMetaTableEntityDTODataReturn.getCode())) {
            throw new ForestBaseException(platMetaTableEntityDTODataReturn.getErrorMsg());
        }
        PlatMetaTableEntityDTO platMetaTableEntityDTO = platMetaTableEntityDTODataReturn.getData();
        if (TABLE_NAME_SHIPINJIANKONG.equals((platMetaTableEntityDTO.getPrefix() + platMetaTableEntityDTO.getCode()))) {
            CameraVO info = cameraInfoService.info(id);
            List<Map<Object, Object>> metaField = new ArrayList<>();
            metaField.add(MapUtil.builder().put("code", "cameraRadius").put("name", "监控半径").build());
            metaField.add(MapUtil.builder().put("code", "isDelete").put("name", "是否有效 1-有效 0-删除").build());
            metaField.add(MapUtil.builder().put("code", "latitude").put("name", "纬度").build());
            metaField.add(MapUtil.builder().put("code", "updateTime").put("name", "更新时间").build());
            metaField.add(
                    MapUtil.builder().put("code", "type").put("name", "监控类型 1防火监控 2防盗监控 3卡口监控 同 cameraType").build());
            metaField.add(MapUtil.builder().put("code", "updateId").put("name", "更新人id").build());
            metaField.add(MapUtil.builder().put("code", "areaCode").put("name", "所属行政区划").build());
            metaField.add(MapUtil.builder().put("code", "areaName").put("name", "所属行政区划名称").build());
            metaField.add(MapUtil.builder().put("code", "towerHeight").put("name", "塔高").build());
            metaField.add(MapUtil.builder().put("code", "createTime").put("name", "创建时间").build());
            metaField.add(MapUtil.builder().put("code", "createId").put("name", "创建人").build());
            metaField.add(MapUtil.builder().put("code", "online").put("name", "是否在线 1在线 0离线").build());
            metaField.add(MapUtil.builder().put("code", "id").put("name", "ID").build());
            metaField.add(MapUtil.builder().put("code", "isControl").put("name", "是否云台控制 1-是 2-否").build());
            metaField.add(MapUtil.builder().put("code", "placeName").put("name", "地址").build());
            metaField.add(MapUtil.builder().put("code", "cameraName").put("name", "视频监控名称").build());
            metaField.add(MapUtil.builder().put("code", "cameraType").put("name",
                    "监控类型 1防火监控 2防盗监控 3卡口监控 3-防盗 同 type").build());
            metaField.add(MapUtil.builder().put("code", "longitude").put("name", "经度").build());
            metaField.add(MapUtil.builder().put("code", "equipmentType").put("name", "设备类型 0云台 1球机 2枪机").build());
            metaField.add(MapUtil.builder().put("code", "frameType").put("name", "监控画面类型 0可见光 1热成像").build());
            metaField.add(MapUtil.builder().put("code", "code").put("name", "字段内容和id相同").build());
            metaField.add(MapUtil.builder().put("code", "cameraId").put("name", "可见光Id,热成像id 逗号拼接，可见光id在前").build());
            metaField.add(MapUtil.builder().put("code", "token").put("name", "可见光token,热成像token 逗号拼接，可见光id在前").build());
            Map<String, Object> result = new HashMap<>();
            result.put("data", info);
            result.put("metaField", metaField);
            return result;
        }

        //数据
        DataReturn dataReturn = remoteDisposeService.dateSelectByService(tableId, "/type/detail", null, null, null,
                null, id, null);
        if (!ResultCode.SUCCESS.getCode().equals(dataReturn.getCode())) {
            throw new ForestBaseException(dataReturn.getErrorMsg());
        }
        Object data = dataReturn.getData();

        //字段描述
        DataReturn<List<PlatMetaFieldEntity>> listDataReturn = remoteDisposeService.selectTableAndFilesByTableId(
                tableId);
        if (!ResultCode.SUCCESS.getCode().equals(listDataReturn.getCode())) {
            throw new ForestBaseException(listDataReturn.getErrorMsg());
        }
        List<PlatMetaFieldEntity> metaFieldEntities = listDataReturn.getData();
        List<Map<String, Object>> metaField = new ArrayList<>();
        metaFieldEntities.forEach(platMetaFieldEntity -> {
            Map<String, Object> item = new HashMap<>();
            item.put("code", platMetaFieldEntity.getCode());
            item.put("name", platMetaFieldEntity.getName());
            metaField.add(item);
        });

        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        result.put("metaField", metaField);
        return result;
    }

    /**
     * 物资分类（过滤“物资设备”）
     *
     * @param qryResourceCatRequest qryResourceCatRequest
     *
     * @return QryResourceCatModel
     */
    @Override
    public List<QryResourceCatModel> qryResourceCat(QryResourceCatRequest qryResourceCatRequest) {
        List<QryResourceCountModel> resourceCountModels = qryResourceCount(
                QryResourceCountRequest.builder().districtCode(qryResourceCatRequest.getDistrictCode()).build());
        List<QryResourceCatModel> qryResourceCatModels = new ArrayList<>();
        resourceCountModels.forEach(qryResourceCountModel -> {
            List<QryResourceCountModel> qryResourceCountModelChild = qryResourceCountModel.getChild();
            List<QryResourceCatModel> child = new ArrayList<>();
            qryResourceCountModelChild.forEach(qryResourceCountModel1 -> {
                child.add(QryResourceCatModel.builder()
                        .id(qryResourceCountModel1.getId())
                        .catName(qryResourceCountModel1.getCatName())
                        .rank(qryResourceCountModel1.getRank())
                        .child(new ArrayList<>())
                        .build());
            });
            qryResourceCatModels.add(QryResourceCatModel.builder()
                    .id(qryResourceCountModel.getId())
                    .catName(qryResourceCountModel.getCatName())
                    .rank(qryResourceCountModel.getRank())
                    .child(child)
                    .build());
        });

        return qryResourceCatModels;
    }

    /**
     * 设备分类
     *
     * @param qryEquipmentCatRequest qryEquipmentCatRequest
     *
     * @return QryEquipmentCatModel
     */
    @Override
    public List<QryEquipmentCatModel> qryEquipmentCat(QryEquipmentCatRequest qryEquipmentCatRequest) {
        List<QryResourceEquipmentCountModel> resourceCountModels = qryResourceEquipmentCount(
                QryResourceEquipmentCountRequest.builder().districtCode(
                        qryEquipmentCatRequest.getDistrictCode()).build());
        List<QryEquipmentCatModel> qryResourceCatModels = new ArrayList<>();
        resourceCountModels.forEach(qryResourceCountModel -> {
            List<QryResourceEquipmentCountModel> qryResourceCountModelChild = qryResourceCountModel.getChild();
            List<QryEquipmentCatModel> child = new ArrayList<>();
            qryResourceCountModelChild.forEach(qryResourceCountModel1 -> {
                child.add(QryEquipmentCatModel.builder()
                        .id(qryResourceCountModel1.getId())
                        .catName(qryResourceCountModel1.getCatName())
                        .rank(qryResourceCountModel1.getRank())
                        .child(new ArrayList<>())
                        .build());
            });
            qryResourceCatModels.add(QryEquipmentCatModel.builder()
                    .id(qryResourceCountModel.getId())
                    .catName(qryResourceCountModel.getCatName())
                    .rank(qryResourceCountModel.getRank())
                    .child(child)
                    .build());
        });

        return qryResourceCatModels;
    }

}
